package cn.pfz.controller;

import cn.pfz.Service.IEmployeeSerives;
import cn.pfz.Service.IPermissionSerives;
import cn.pfz.Service.IRolePermissionSerives;
import cn.pfz.Service.IRoleSerives;
import cn.pfz.annotation.RequiredPermission;
import cn.pfz.domain.*;
import cn.pfz.query.EmployeeQuery;
import cn.pfz.query.RoleQuery;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    //角色的
    @Autowired
    private IRoleSerives iRoleSerives;

    //关联表的
    @Autowired
    private IRolePermissionSerives rolePermissionSerives;

    @Autowired
    private IPermissionSerives iPermissionSerives;



    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") RoleQuery qo){
        PageInfo<Role> list = iRoleSerives.list(qo);

        model.addAttribute("result",list);
        model.addAttribute("qo",qo);
        return "role/list";
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role department, Long[] ids) {


        if(department.getId()!=null){
            //修改
            rolePermissionSerives.deleteByPermission_role(department.getId());
            for (Long id : ids) {
                rolePermissionSerives.insert(new RolePermission(department.getId(),id));
            }
            iRoleSerives.updateByPrimaryKey(department);
        }else {
            //新增
            rolePermissionSerives.deleteByPermission_role(department.getId());
            for (Long id : ids) {
                rolePermissionSerives.insert(new RolePermission(department.getId(),id));
            }
            iRoleSerives.insert(department);
        }

        return "redirect:/role/list";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        iRoleSerives.deleteByPrimaryKey(id);
        return JsonResult.success(null);
    }

    @RequestMapping("/input")
    public String input(Model model, Long id) {
        List<Permission> rolePermissions = iPermissionSerives.selectAll();
        model.addAttribute("roleList", rolePermissions);
        if (id == null) {
            return "role/input";
        } else {
            Role employee = iRoleSerives.selectByPrimaryKey(id);
            model.addAttribute("curremp", employee);
            List<Permission> rs = iRoleSerives.selectByRole(id);
            model.addAttribute("selfRoles", rs);
            return "role/input";
        }

    }


}
